﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Xml;
using System.Web;
using System.IO;
using System.Diagnostics;
using MySql.Data.MySqlClient;

namespace HBM_App
{
    public partial class frmMainMenu : Form
    {
        Socket s;
        Socket s2;
        Thread m_S1Respond;
        Thread m_S2Respond;
        Thread m_St;
        Thread m_Restart;

        String m_ip_add;
        string m_mySQLConn = "SERVER=host244.hostmonster.com; " +
                             "Database=showandt_HBM;" +
                             "UID=showandt_tphbm;" +
                             "PASSWORD=gohbm;";
        int m_port;

        int unitCount = 1;

        int cid;

        String m_ip_add2;
        int m_port2;

        byte[] buff = { 0x1, 0x2, 0x3, 0x4 };

        public frmMainMenu()
        {
            InitializeComponent();

    //        HiddingXMLFile();
            Thread.Sleep(1000);
            foreach (System.Diagnostics.Process myProc in System.Diagnostics.Process.GetProcesses())
            {
                DateTime currentTime = new DateTime();
                currentTime = DateTime.Now.Subtract(new TimeSpan(0, 0, 5));
                if (myProc.ProcessName == "HBM_App" && myProc.StartTime < currentTime)
                    myProc.Kill();
            }

            m_St = new Thread(new ThreadStart(StartProcess));
            m_St.Start();

           // m_Restart = new Thread(new ThreadStart(CheckRestart));
            //m_Restart.Start();
        }

        private void CheckRestart()
        {
            Thread.Sleep(1800000); 
            Process.Start(Application.ExecutablePath);
            s.Close();
            s2.Close();
            Application.Exit();
        }

        private void HiddingXMLFile()
        {
            System.IO.FileInfo _file = new System.IO.FileInfo("XMLUnits.xml");
            _file.Attributes = System.IO.FileAttributes.Hidden;
        }

        private void StartProcess()
        {
            while (m_St.IsAlive)
            {
                    XmlDocument doc = new XmlDocument();
                    try{
                    doc.Load(Application.StartupPath + "\\XMLUnits.XML");
                    }catch(Exception e)
                    {
                        //MessageBox.Show(e.Message);
                    }

                    XmlNodeList LT_unit = doc.SelectNodes("//unit");

                    cid = -2;

                    foreach (XmlNode unit in LT_unit)
                    {
                        try
                        {

                        cid = cid + 5;

                        String rearName = unit["rear"].Attributes["name"].Value;

                        XmlNode ip_add = unit["rear"].SelectSingleNode("ip_add");
                        m_ip_add = ip_add.InnerText;

                        XmlNode port = unit["rear"].SelectSingleNode("port");
                        m_port = Convert.ToInt32(port.InnerText);

                        String sideName = unit["side"].Attributes["name"].Value;

                        XmlNode ip_add2 = unit["side"].SelectSingleNode("ip_add");
                        m_ip_add2 = ip_add2.InnerText;

                        XmlNode port2 = unit["side"].SelectSingleNode("port");
                        m_port2 = Convert.ToInt32(port2.InnerText);



                        IPAddress hostadd = IPAddress.Parse(m_ip_add);

                        IPEndPoint EPhost = new IPEndPoint(hostadd, m_port);

                        IPAddress hostadd2 = IPAddress.Parse(m_ip_add2);

                        IPEndPoint EPhost2 = new IPEndPoint(hostadd2, m_port2);

                        s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                        s.Connect(EPhost);

                        s2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        s2.Connect(EPhost2);

                       try
                        {
                            if (s.Connected)
                            {

                                Byte[] cmd1 = { 0xFF, 0x8, buff[0], 0x9 };
                                Byte[] cmd2 = { 0xFF, 0x8, buff[1], 0xA };
                                Byte[] cmd3 = { 0xFF, 0x8, buff[2], 0xB };
                                Byte[] cmd4 = { 0xFF, 0x8, buff[3], 0xC };

                                s.Send(cmd1);
                                Thread.Sleep(200);
                                s.Send(cmd2);
                                Thread.Sleep(200);
                                s.Send(cmd3);
                                Thread.Sleep(200);
                                s.Send(cmd4);

                                try
                                {

                                    m_S1Respond = new Thread(new ThreadStart(StartRecieve));
                                    m_S1Respond.Start();
                                    Thread.Sleep(10000);

                                    if (m_S1Respond.IsAlive)
                                        m_S1Respond.Abort();
                                }
                                catch (Exception e)
                                {
                                }
                                finally
                                {
                                    s.Close();
                                }
                            }
                        }
                        catch { s.Close(); }

                       s.Dispose();



                        try
                        {
                            if (s2.Connected)
                            {
                                Byte[] cmd1 = { 0xFF, 0x8, buff[0], 0x9 };
                                Byte[] cmd2 = { 0xFF, 0x8, buff[1], 0xA };
                                Byte[] cmd3 = { 0xFF, 0x8, buff[2], 0xB };
                                Byte[] cmd4 = { 0xFF, 0x8, buff[3], 0xC };

                                s2.Send(cmd1);
                                Thread.Sleep(500);
                                s2.Send(cmd2);
                                Thread.Sleep(500);
                                s2.Send(cmd3);
                                Thread.Sleep(500);
                                s2.Send(cmd4);

                             


                                try
                                {
                                    m_S2Respond = new Thread(new ThreadStart(StartRecieve2));
                                    m_S2Respond.Start();
                                    Thread.Sleep(10000);

                                    if (m_S2Respond.IsAlive)
                                        m_S2Respond.Abort();
                                }
                                catch (Exception e)
                                {
                                }
                                finally
                                {
                                    s2.Close();
                                }
                            }
                        }
                        catch {s2.Close();}

                        s2.Dispose();

                        }
                        catch (Exception e)
                        {
                            //MessageBox.Show(e.Message);
                            //if (richTextBox1.InvokeRequired)
                            //{

                            //    richTextBox1.Invoke(new MethodInvoker(delegate
                            //    {
                            //        richTextBox1.Select(0, 0);
                            //        richTextBox1.SelectionColor = Color.Red;
                            //        richTextBox1.SelectedText = unitCount++ + " - Failed" + " - " + DateTime.Now.ToString() + Environment.NewLine;
                            //    }));
                            //}
                        }
                    }
                
                
                unitCount = 1;
                //Thread.Sleep(200000); //5 Minutes
                 Thread.Sleep(30000); //30 Seconds
           //      Thread.Sleep(3000); 
            }
        }

        private void StartRecieve()
        {
            Byte[] receive = new Byte[4];
            Byte[] receive1 = new Byte[4];
            Byte[] receive2 = new Byte[4];
            Byte[] receive3 = new Byte[4];

            try
            {
                s.Receive(receive, receive.Length, 0);
                s.Receive(receive1, receive.Length, 0);
                s.Receive(receive2, receive.Length, 0);
                s.Receive(receive3, receive.Length, 0);
            }
            catch (Exception)
            {
            }

            UpdateSite(receive, receive1, receive2, receive3, false);
        }       
 
        private void StartRecieve2()
        {
            Byte[] receive = new Byte[4];
            Byte[] receive1 = new Byte[4];
            Byte[] receive2 = new Byte[4];
            Byte[] receive3 = new Byte[4];
 
            try
            {
                s2.Receive(receive, receive.Length, 0);
                s2.Receive(receive1, receive.Length, 0);
                s2.Receive(receive2, receive.Length, 0);
                s2.Receive(receive3, receive.Length, 0);
            }
            catch (Exception)
            {
            }
            UpdateSite(receive, receive1, receive2, receive3, true);
            //s2.Close();
        }

        private void UpdateSite(byte[] receive, byte[] receive1, byte[] receive2, byte[] receive3, bool vertical)
        {
            int i = 0;
            int j = 4;

            if (vertical)
            { i = 4; j = 5; }

            MySqlConnection conn = new MySqlConnection(m_mySQLConn);

            string c_id = cid.ToString();

            for (; i < j; i++)
            {
                string bk_temp = ConvertCelsiusToFahrenheit(receive[2]);
                string ctrlbrd_tmp = ConvertCelsiusToFahrenheit(receive1[2]);
                string ambnt_lght = receive2[2].ToString();
                string dty_cyle = receive3[2].ToString();

                string displayName = GetDisplayName(i);

                string updateString = "datatype=" + "3" +
                                    "&c_id=" + c_id +
                                    "&ds_tpe=" + Convert.ToString(i) +
                                    "&bk_tmp=" + bk_temp +
                                    "&crnt_sts=" + "online" +
                                    "&ds_nme=" + displayName +
                                    "&ctrlbrd_tmp=" + ctrlbrd_tmp +
                                    "&dty_cyle=" + dty_cyle +
                                    "&ip_ad=" + m_ip_add +
                                    "&ambnt_lght=" + ambnt_lght +
                                    "&ds_tmp=na" +
                                    "&inpt_srce=na" +
                                    "&brght=na";

                //string insertCom = "INSERT INTO `showandt_HBM`.`tbl_component_display` " +
                //                   "(`component_id`," +
                //                   "`display_type`," +
                //                   "`display_name`," +
                //                   "`ip_address`," +
                //                   "`last_ping`," +
                //                   "`current_status`," +
                //                   "`display_temp`," +
                //                   "`backlight_temp`," +
                //                   "`ctrl_board_temp`," +
                //                   "`duty_cycle`," +
                //                   "`ambient_light`," +
                //                   "`brightness`," +
                //                   "`input_source`)" +
                //                   " VALUES " +
                //                   "(" + c_id + "," +
                //                   i.ToString() + "," +
                //                   "'" + displayName + "'," +
                //                   "'" + m_ip_add + "'," +
                //                   "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," +
                //                   "'" + "online'," +
                //                   "'" + "na'," +
                //                   "'" + bk_temp + "<sup>o</sup>F'," +
                //                   "'" + ctrlbrd_tmp + "<sup>o</sup>F'," +
                //                   "'" + dty_cyle +"'," +
                //                   "'" + ambnt_lght +"'," +
                //                   "'" + "na'," +
                //                   "'" + "na');" ;




                //try
                //{
                //    // Update employees
                //    //string queryCom = insertCom + insertCom2;
                //    conn.Open();
                //    MySqlCommand cmd = new MySqlCommand(insertCom, conn);
                //    MySqlDataReader reader = cmd.ExecuteReader();
                //    cmd.CommandType = System.Data.CommandType.Text;
                //    while (reader.Read() != false)
                //    {
                //        Console.WriteLine(reader.FieldCount);
                //    }

                //    reader.Close();
                //}
                //catch (Exception e)
                //{
                //    Console.WriteLine("Error: " + e);
                //}

                string url = "http://www.showandtell.com/hbm/ServerDataAPI.php?" + updateString;

                try
                {
                    WebRequest wrGETURL;
                    wrGETURL = WebRequest.Create(url);

                    Stream objStream;
                    objStream = wrGETURL.GetResponse().GetResponseStream();

                    StreamReader objReader = new StreamReader(objStream);

                    string sLine = "";
                    int s = 0;

                    while (sLine != null)
                    {
                        s++;
                        sLine = objReader.ReadLine();
                        if (sLine != null)
                        {
                            if (richTextBox1.InvokeRequired)
                            {

                                richTextBox1.Invoke(new MethodInvoker(delegate
                                {
                                    richTextBox1.Select(0, 0);
                                    richTextBox1.SelectionColor = Color.Black;
                                    richTextBox1.SelectedText = "DateTime : " + DateTime.Now + Environment.NewLine;
                                    richTextBox1.SelectedText = "URL Response -- Component ID: " + cid + " DisplayID:" + i.ToString() + " Result:" + sLine + Environment.NewLine;
                                    //Console.WriteLine("URL Response {0}:{1}:{2}", cid, i.ToString(), sLine);
                                }));
                            }

                            break;
                            //logger.Info("URL Response {0}:{1}", i, sLine);
                        }

                    }



                    //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    //StreamReader resStream = new StreamReader(response.GetResponseStream());
                    //string websiteReturn = resStream.ReadToEnd();
                    // MessageBox.Show(resStream.ReadToEnd() + "\n" + DateTime.Now);
                }
                catch (Exception e)
                {
                    //MessageBox.Show(e.Message + "\n" + DateTime.Now);
                }
                Thread.Sleep(500);
            }

            //string insertCom2 = "INSERT INTO `showandt_HBM`.`tbl_component_state`" +
            //                       "(`component_id`," +
            //                       "`state`," +
            //                       "`datetime`," +
            //                       "`created`)" +
            //                       "VALUES " +
            //                       "(" + c_id + "," +
            //                       "'green'," +
            //                       "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'," +
            //                       "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "');";



            //try
            //{
            //    // Update employees
            //    //string queryCom = insertCom + insertCom2;
            //    MySqlCommand cmd = new MySqlCommand(insertCom2, conn);
            //    MySqlDataReader reader = cmd.ExecuteReader();
            //    cmd.CommandType = System.Data.CommandType.Text;
            //    while (reader.Read() != false)
            //    {
            //        Console.WriteLine(reader.FieldCount);
            //    }

            //    reader.Close();
            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine("Error: " + e);
            //}
            //finally
            //{
            //    conn.Close();
            //}
        }

        public string ConvertCelsiusToFahrenheit(double c)
        {
            return Convert.ToString(((9.0 / 5.0) * c) + 32);
        }

        private string GetDisplayName(int i)
        {
            switch (i)
            {
                case 0:
                    return "H1";
                case 1:
                    return "H2";
                case 2:
                    return "H3";
                case 3:
                    return "H4";
                case 4:
                    return "V";
                default:
                    return "";
            }
        }

        private void frmMainMenu_FormClosing(object sender, FormClosingEventArgs e)
        {
            //m_S2Respond.Abort();
            //m_S1Respond.Abort();
            //s.Close();
            //s2.Close();

            foreach (System.Diagnostics.Process myProc in System.Diagnostics.Process.GetProcesses())
            {
                if (myProc.ProcessName == "HBM_App")
                    myProc.Kill();
            }
            Application.Exit();
        }
    }
}